/**
 * @description 上传相关控制
 */
const dayjs = require("dayjs")
const { IP, PROTOCOL, PORT, staticURL, assetsDir } = require("../../config")
const fs = require("fs")

const { controller_save } = require("../system/materialManager/materialManager.CONTROLLER")

// 文件流生成，获取图片url处理
const getFileStream = async ({
    // fileName = null,
    files = null,
    id = null

}) => {
    const { file } = files
    const fileName = file.originalFilename;
    const size=file.size;
    console.log("传进来的文件：\n", files)
    const reader = fs.createReadStream(file.filepath);
    const ext = file.originalFilename.split('.').pop(); // 获取上传文件扩展名


    /**判断二级目录，如果是图片后缀，则放file_images里面，否则放file目录 */
    let fileDirName = "file";
    if (ext === "png" || ext === "jpeg" || ext === "jpg" || ext === "3gp") {
        fileDirName = "file_images";
    }

    // 判断目录是否存在，不存在则创建目录
    const savedDir = `${assetsDir}/${fileDirName}/${dayjs().format('YYYY-MM-DD')}/`
    if (fs.existsSync(savedDir)) {
    } else {
        fs.mkdirSync(savedDir)
    }
    const upStream = fs.createWriteStream(`${savedDir}${id}.${ext}`)
    reader.pipe(upStream)
    let imgUrl = `/bil_Ste_static/${fileDirName}/${dayjs().format('YYYY-MM-DD')}/${id}.${ext}`

    await controller_save({
        id: id,
        createDate: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        fileType: ext,
        path: savedDir,
        fileName: fileName,
        size:size,
        uploader: "system"
    })
    return {
        url: imgUrl,
        name: fileName,
        uid: id,
        // status: 'done',
    }
}


/**@description 根据id文件名删除一个文件 */
const deleteFile_controller = async (filePath) => {
    fs.unlink(filePath, (error) => {
        if (error) {
            return {
                code: 123,
                msg: "删除失败"
            }
        }
        return {
            code: 0,
            msg: "删除成功"
        }
    })
}


module.exports = {
    getFileStream,
    deleteFile_controller
}